package com.sunny.passbook.security;

import com.sunny.passbook.constant.MyContants;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器
 */
public class AuthCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String tocken = httpServletRequest.getHeader(MyContants.TOKEN_STRING);
        if(StringUtils.isEmpty(tocken)) {
            throw new Exception("handle 中缺少 " + MyContants.TOKEN_STRING + " !");
        }

        if(!tocken.equals(MyContants.TOKEN)) {
            throw new Exception("handle 中缺少 " + MyContants.TOKEN_STRING + " 错误!");
        }

        AccessContext.setTocken(tocken);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        AccessContext.clearAccessKey();
    }
}
